package cn.wolfcode.wolf2w.business.repository;

import cn.wolfcode.wolf2w.business.domain.Strategy;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class StrategyRepository {

    private static final String INDEX ="strategy";
    @Autowired
    private RestHighLevelClient client;

    public List<Strategy> search(String query, int size) throws IOException {
        SearchSourceBuilder ssb=new SearchSourceBuilder()
                .query(QueryBuilders.multiMatchQuery( query, "title","subTitle","summary"))
                .size(size);
        SearchRequest request = new SearchRequest(INDEX).source(ssb);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        List<Strategy> result = new ArrayList<>();

        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String title = sourceAsMap.get("title").toString();
            String subTitle = sourceAsMap.get("subTitle").toString();
            String summary = sourceAsMap.get("summary").toString();
            Strategy strategy = new Strategy(null, title, subTitle, summary);
            result.add(strategy);
        }
        return result;
    }
}
